package com.duqc.util.ip;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.SFTPv3DirectoryEntry;
import com.duqc.web.entity.RegionalNetwork;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Searcher
 * @Description Searcher
 * @Author duqc
 * @Date 2022/7/19
 **/
@Slf4j
public class SearcherUtil {

    /**
     * 封装地址信息
     *
     * @param ipAddress
     * @return RegionalNetwork
     */
    public static RegionalNetwork regionalAndNetwork(String ipAddress) {
        if (StringUtils.isBlank(ipAddress)) {
            return new RegionalNetwork();
        }
        SearcherUtil searcherUtil = new SearcherUtil();
        String search = searcherUtil.search(ipAddress);
        if (StringUtils.isBlank(search)) {
            return new RegionalNetwork("0", "0", "0", "0", "0", ipAddress);
        }
        String[] split = search.split("\\|");
        return new RegionalNetwork(split[0], split[1], split[2], split[3], split[4], ipAddress);
    }

    /**
     * 通过IP解析地址
     *
     * @param ipAddress
     * @return String
     */
    public String search(String ipAddress) {
        if (StringUtils.isBlank(ipAddress)) {
            return null;
        }
        String dbPath = this.getClass().getClassLoader().getResource("ip2region.xdb").getPath();
//        String dbPath = "/www/server/java/summarize/xdb/ip2region.xdb";
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff;
        try {
            cBuff = Searcher.loadContentFromFile(dbPath);
        } catch (Exception e) {
            log.info("failed to load content from `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.info("failed to create content cached searcher: %s\n", e);
            return "";
        }

        // 3、查询
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ipAddress);
            long cost = TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime));
            log.info(String.format("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost));
            return region;
        } catch (Exception e) {
            log.info("failed to search({}): {}}\n", ipAddress, e);
        }
        return "";
    }

    public static void main(String[] args) {
        //创建远程连接，默认连接端口为22，如果不使用默认，可以使用方法
        //new Connection(ip, port)创建对象
        String ip = "120.46.203.0";
        String usr = "root";
        String pwd = "Dqcjszyrx123";
        //int port=22;
        Connection conn = null;
        String date = "";
        //所要查询的目录
        ArrayList<String> filesNameList = new ArrayList<String>();
        try {
            //连接远程服务器
            // 连接部署服务器
            conn = new Connection(ip);
            conn.connect();
            //使用用户名和密码登录
            boolean b = conn.authenticateWithPassword(usr, pwd);
            if (!b) {
                throw new IOException("Authentication failed.");
            } else {
                SFTPv3Client sft = new SFTPv3Client(conn);
                Vector<?> v = sft.ls("/www/server/java/summarize");
                for (int i = 0; i < v.size(); i++) {
                    SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry();
                    s = (SFTPv3DirectoryEntry) v.get(i);
                    //文件名
                    String filename = s.filename;
                    filesNameList.add(filename);
                }
            }
            conn.close();
        } catch (IOException e) {
            System.err.printf("用户%s密码%s登录服务器%s失败！", usr, pwd, ip);
            e.printStackTrace();
        }

        System.out.println("filesNameList" + filesNameList);
    }

}
